<?php
$loader->requireOnce('includes/Insurance/InsuranceRule.class.php');
$loader->requireOnce('includes/DiscountManager/IDiscountable.interface.php');
class InsuranceCalculator implements IDiscountable {
    private $insuranceRule;

    function __construct($objRule = null) {
    	$this->insuranceRule   =   $objRule;
    }

    public function setInsuranceRule($objRule) {
    	$this->insuranceRule   =   $objRule;
    }

    /**
     * Calculate insurance payment for a BillableStorage object
     *
     * @param BillStorage $objStorage
     */
    public function discount(&$objStorage) {
    	$objInfo   =   $objStorage->getInsuranceInfo();
        foreach ($objStorage->getItemList() as $subList) {
        	foreach ($subList as &$item) {
                $ruleData   =   $this->insuranceRule->getRuleData($item);
                self::calculateItemPayment($item, $ruleData, $objInfo);
        	}
        }
    }

    /**
     * Calculate insurance payment for a BillableItem object with given RuleData object
     *
     * @param BillableItem $billableItem BillableItem object
     * @param RuleData $ruleData RuleData object
     * @param InsuranceInfo $insuranceInfo InsuranceInfo object
     */
    private function calculateItemPayment(&$billableItem, $ruleData, $insuranceInfo) {
    	if (!$ruleData) {
            return;
        }

        // Check if 36-month condition required
        if (!$ruleData->isConditonRequired() || ($insuranceInfo->getPaidFor36Month() > 0)) {

            $amount =   $billableItem->getQuantity() * $billableItem->getInsuranceRenumeration() * $ruleData->getPercent()/100;
            if ($ruleData->getMaxAmount() > 0) {
                $amount =   min(array($amount, $ruleData->getMaxAmount()));
            }

            // Set payment data to the billable item
            $billableItem->setInsurancePrice($amount);
        }
    }
}
?>